from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response

from tensquare.apps.user.models import User
from tensquare.apps.user.serializers import UserInfoSerializer,UserPasswordSerializer,UserLabelSerializer
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView, RetrieveUpdateAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

class UserInfoView(RetrieveUpdateAPIView):
    serializer_class = UserInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        user = self.request.user
        replies = user.replies.all()
        user.answer_question = []
        for item in replies:
            if item.type == 2: # 回答的评论
                user.answer_question.append(item)
        return user

class UserPasswordView(UpdateAPIView):
    serializer_class = UserPasswordSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

class UserLikeView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self,request,userid):
        user = self.request.user
        idol = User.objects.get(id=userid)
        if idol in user.idols.all():
            return Response({"success": False, "message": "请不要重复取消关注"}, status=400)

        user.idols.add(idol)
        user.save()
        return Response({"success": True, "message": "关注成功"})

    def delete(self, request, userid):
        user = self.request.user
        idol = User.objects.get(id=userid)
        if idol not in user.idols.all():
            return Response({"success": False, "message": "没有关注该用户"}, status=400)

        user.idols.remove(idol)
        user.save()
        return Response({"success": True, "message": "取消关注成功"})


class UserLabelView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = UserLabelSerializer

    def get_object(self):
        return self.request.user